package com.sites.cms.account;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.sites.cms.permission.Remark;
import com.sites.cms.role.RoleService;
import com.sites.common.SiteInfo;
import com.sites.common.model.Account;
import com.sites.common.model.Role;

/**
 * 用户管理控制器
 * 
 * @author zyg
 * 2020年1月4日 下午2:53:28
 */
@Before(AccountInterceptor.class)
public class AccountController extends Controller {

	@Inject
	private AccountService srv;
	@Inject
	private RoleService roleSrv;
	
	@Remark("菜单：用户管理")
	public void enterAccountMng(){
		int page = getParaToInt("page", 1);
		int limit = getParaToInt("limit", 8);
		String nickName = getPara("nickName", "");
		String userName = getPara("userName", "");
		int status = getParaToInt("status", -1);
		keepPara();//保存参数
		Page<Account> accountPage = srv.queryAccountsPage(page, limit, nickName, userName, status);
		setAttr("accountPage", accountPage);
		render("pageAccountMng.html");
	}
	
	@Remark("菜单：新建用户")
	public void enterAccountAdd(){
		render("pageAccountAdd.html");
	}
	
	@Remark("按钮：保存用户")
	public void saveAccount(){
		Account account = getModel(Account.class, "");
		Ret ret = srv.saveAccount(account);
		renderJson(ret);
	}
	
	@Remark("按钮：编辑用户")
	public void enterAccountEdit(){
		int id = getParaToInt(0);
		Account account = srv.getById(id);
		setAttr("a", account);
		render("pageAccountEdit.html");
	}
	
	@Remark("按钮：更新用户")
	public void updateAccount(){
		Account account = getModel(Account.class, "");
		Ret ret = srv.updateAccount(account);
		renderJson(ret);
	}
	
	@Remark("按钮：删除用户")
	public void deleteAccount(){
		int id = getInt(0);
		Ret ret = srv.deleteAccount(id);
		renderJson(ret);
	}
	
	@Remark("按钮：用户分配角色")
	public void enterAccountRole(){
		int id = getParaToInt(0);
		Account account = srv.getById(id);
		List<Role> roleList = roleSrv.queryAllRoles();
		List<Role> accountRoleList = srv.getAccountRoles(id);
		roleList = srv.markAccountRole(roleList, accountRoleList);
		
		setAttr("a", account);
		setAttr("roleList", roleList);
		
		render("pageAccountRole.html");
	}
	
	@Remark("按钮：更新用户角色")
	public void updateAccountRole(){
		int accountId = getParaToInt(0);
		int roleId = getParaToInt(1);
		boolean checked = getParaToBoolean(2);
		Ret ret = srv.updateAccountRole(accountId, roleId, checked);
		renderJson(ret);
	}
	
	@Remark("按钮：修改个人密码")
	public void enterPwdEdit(){
		Account account = (Account)getSessionAttr(SiteInfo.account);
		setAttr("a", account);
		render("pagePwdEdit.html");
	}
	
	@Remark("按钮：更新个人密码")
	@Before(UpdatePwdValidator.class)
	public void updatePwd(){
		int id = getParaToInt("id");
		String password = getPara("password");
		Ret ret = srv.updatePwd(id, password);
		renderJson(ret);
	}
}
